<template>
  <div class="department-container">
    <div class="app-container">
      <!-- 自定义头部 -->
      <el-card>
        <!-- 具体页面结构 -->
        <PageTools>
          <template #left>
            总记录条数:{{ total }}条
          </template>

          <template #right>
            <!-- {{  }} -->
            <el-button v-allow="'import'" type="warning" @click="$router.push('/import')">导入Excel</el-button>
            <el-button v-allow="'export'" type="danger" @click="exportExcelFile">导出Excel</el-button>
            <el-button type="primary" @click="addE">新增员工</el-button>
          </template>
        </PageTools>
      </el-card>

      <!-- 内容区 -->
      <el-card>
        <el-table border :data="formData" :stripe="true">
          <el-table-column label="序号" type="index">
            <template v-slot="{$index}">
              {{ $index + 1 +((p.page - 1) * p.size) }}
            </template>
          </el-table-column>

          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" prop="" width="150px">
            <template v-slot="{row}">
              <ImageHolder>
                <template #error>
                  <img :src="row.staffPhoto" class="img_container">
                </template>
              </ImageHolder>
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable prop="workNumber" />

          <el-table-column label="聘用形式">
            <template v-slot="{row}">
              <!-- {{ row.formOfEmployment | typeEmployment }} -->
              {{ formatType(row.formOfEmployment) }}
            </template>
          </el-table-column>

          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <el-table-column label="操作" width="280">

            <template v-slot="{row}">
              <el-row type="flex" justify="center">
                <!-- <el-col :span="8"><el-link type="primary" @click="$router.push(`/detail?id=${row.id}`)">查看</el-link></el-col> -->
                <el-col :span="8"><el-link type="primary" @click="$router.push({path:'/detail', query: {id: row.id} })">查看</el-link></el-col>
                <el-col :span="8"><el-link type="primary" @click="setRole(row.id)">分配角色</el-link></el-col>
                <el-col :span="8"><el-link type="primary" @click="deleteE(row.id)">删除</el-link></el-col>
              </el-row>
            </template>
          </el-table-column>
        </el-table>

        <el-row type="flex" justify="center" style="height:60px" align="middle">
          <el-pagination
            layout="total, sizes, prev, pager, next"
            :total="total"
            :page-size="p.size"
            :page-sizes="[3, 6, 9, 10]"
            :current-page.sync="p.page"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          />
        </el-row>
      </el-card>

      <!-- 弹窗 -->
      <el-dialog
        title="新增员工"
        :visible.sync="dialogVisible"
        width="50%"
        @close="closeDialogCallBack"
      >
        <EmpDialog ref="dialogForm" :close-dialog="closeDialog" @success1="success1" />
      </el-dialog>

      <!-- 分配角色弹窗 -->
      <el-dialog
        title="新增员工"
        :visible.sync="dialogVisibleRole"
      >
        <AssignRole v-if="dialogVisibleRole" :cur-id="curId" @successAssignRole="successAssignRole" />
      </el-dialog>
    </div>
  </div>
</template>

<script>

import employeesFormatDate from '@/constant/employees'
import { queryEmployessList, deleteEmployeById } from '@/api/employees'

// 引入组件
import EmpDialog from './EmpDialog'
import AssignRole from './AssignRole'

// 将获取到的数组 转换成为一个对象
const TYPE_OBJ = employeesFormatDate.hireType.reduce((pVal, cVal) => {
  pVal[cVal.id] = cVal.value
  return pVal
}, {})
// console.log(TYPE_OBJ)

export default {
  name: '',
  components: {
    EmpDialog,
    AssignRole
  },
  filters: {
    typeEmployment: function(value) {
      if (value === 1 || value === 2) {
        return value === 1 ? '正式工' : '非正式工'
      } else {
        return '未知的值'
      }
    }
  },
  data() {
    return {
      // 数据表格数据
      formData: [],
      // 查询的页数和数量
      p: {
        page: 1,
        size: 10
      },
      total: 0,
      // 弹窗控制器
      dialogVisible: false,
      dialogVisibleRole: false,
      // 当前选择的员工id
      curId: ''
    }
  },
  created() {
    this.getEmployessDate()

  // 测试转换
    // console.log(this.formatType(3))
  },
  methods: {
    // todo 分配角色
    async setRole(id) {
      this.dialogVisibleRole = true
      this.curId = id
    },
    // todo 分配角色成功之后
    successAssignRole() {
      this.dialogVisibleRole = false
    },

    //! 1.获取员工数据列表
    async getEmployessDate() {
      const res = await queryEmployessList(this.p)
      // console.log(res)
      this.formData = res.data.rows
      this.total = res.data.total
    },
    //! 2.删除员工
    deleteE(id) {
      this.$confirm('您确认要删除吗?', '提示', {
        type: 'warning',
        confirmButtonText: '确认删除',
        cancelButtonText: '取消操作'
      })
        .then(
          async() => {
            try {
              const res = await deleteEmployeById(id)
              // console.log(res)
              if (this.total % this.p.size === 1) {
              // this.p.page -= 1
                this.p.page > 1 ? this.p.page -= 1 : this.p.page = 1
              }
              this.getEmployessDate()
              this.$message.success(res.message)
            } catch (error) {
              this.$message.error(error.message)
            }
            // 更新
          },
          () => {
            this.$message.info('您取消了操作!')
          }
        )
    },

    //! 3.新增员工
    addE() {
      this.dialogVisible = true
    },

    // todo exportExcelFile 点击导出excel 文件方法
    exportExcelFile() {
      // 导出文件 英文名 === 中文名
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // data数据
      // const dataArr = [
      //   ['13600000001', '吕勇锐', '1992-08-04', '正式', '2020-01-01', '0001', '总裁办'],
      //   ['13600000002', '袁永安', '1993-08-04', '正式', '2020-01-01', '0002', '总裁办']
      // ]

      //* 1.名字只需要取一次就可以了 拿到数据的对象的第一份 转成英文数组 ,
      //* 2.匹配 map数组中英名 对应的中文value值
      // console.log(Object.keys(this.formData[0]))
      // ['id', 'mobile', 'username', 'password', 'timeOfEntry', 'formOfEmployment', 'workNumber', 'correctionTime', 'departmentName', 'staffPhoto']
      const header = Object.keys(this.formData[0]).map(item => map[item]) // item 是英文名
      // 取出每个对象的值就可以了
      const data = this.formData.map(item => {
        // console.log(item.formOfEmployment)
        const Nitem = { ...item } // 断开引用
        Nitem.formOfEmployment = TYPE_OBJ[Nitem.formOfEmployment]
        // 需要将1or2转换成正式工或者非正式工
        return Object.values(Nitem)
      })
      // console.log('输出 (→_→)  header', header)
      // console.log('输出 (→_→)  data', data)

      import('@/vendor/Export2Excel').then(excel => {
        // excel表示导入的模块对象
        console.log(excel)
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },

    // todo 当点击确认按钮 请求成功之后
    success1() {
      // 关闭弹窗
      this.dialogVisible = false

      // 跳转到新添加的页面
      this.total++
      this.p.page = Math.ceil(this.total / this.p.size)
      console.log(this.p.page)

      // 重新获取数据
      this.getEmployessDate()
    },

    // todo  关闭弹窗的方法
    closeDialog() {
      this.dialogVisible = false
    },
    // todo 关闭弹窗的之后回调 清空表单数据
    closeDialogCallBack() {
      // console.log(this.$refs.dialogForm.$refs.ruleForm)
      this.$refs.dialogForm.$refs.ruleForm.resetFields()
    },

    // todo 点击切换每页数量
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      // 修改了每页数量  重新发送请求渲染
      // 切换条数的时候 将页码默认设置为第一页
      this.p.size = val
      this.p.page = 1
      this.getEmployessDate()
    },
    // todo 点击页码切换
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      // 修改了页码 重新发送请求渲染
      this.p.page = val
      this.getEmployessDate()
    },
    // todo 将数据转换成对应的字符串
    formatType(value) {
      return TYPE_OBJ[value] || '未知的'
    }
  }
}
</script>

<style scoped>
.el-col{
  text-align: center;
}
</style>
